import 'package:flutter/material.dart';
import 'package:flutter_demo/controllers/download_controller.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

import '../utils/const.dart';

class _WebPageController extends GetxController {
  final progress = 0.0.obs;

  setProgress(double p) {
    progress.value = p;
  }
}

class WebPage extends GetWidget<_WebPageController> {
  WebPage({Key? key}) : super(key: key) {
    Get.create(() => _WebPageController());
  }
  final downloadController = Get.find<DownloadController>();

  @override
  Widget build(BuildContext context) {
    InAppWebViewController? _webViewcontroller;
    return WillPopScope(
      child: Scaffold(
        appBar: AppBar(
          title: const Text("下载"),
          leading: InkWell(
            child: const Icon(Icons.close),
            onTap: () {
              Get.back();
            },
          ),
          elevation: 0,
          toolbarHeight: Const.kAppBarHeight,
        ),
        body: Stack(
          children: [
            InAppWebView(
              initialUrlRequest: URLRequest(url: Uri.parse(Get.arguments.toString())),
              initialOptions: InAppWebViewGroupOptions(
                crossPlatform: InAppWebViewOptions(
                  useShouldOverrideUrlLoading: true,
                  useOnDownloadStart: true,
                  mediaPlaybackRequiresUserGesture: false,
                ),
                android: AndroidInAppWebViewOptions(
                  useHybridComposition: true,
                ),
                ios: IOSInAppWebViewOptions(
                  allowsInlineMediaPlayback: true,
                ),
              ),
              onWebViewCreated: (controller) {
                _webViewcontroller = controller;
              },
              androidOnPermissionRequest: (controller, origin, resources) async {
                return PermissionRequestResponse(resources: resources, action: PermissionRequestResponseAction.GRANT);
              },
              onDownloadStartRequest: (controller, request) {
                launchUrl(request.url, mode: LaunchMode.externalApplication);
                Get.back();
                // Get.defaultDialog(
                //   title: "下载",
                //   content: Text(
                //     "是否开始下载${request.url.toString()}?",
                //     maxLines: 4,
                //     overflow: TextOverflow.ellipsis,
                //   ),
                //   onConfirm: () {
                //     Get.log("11111");
                //     downloadController.startDownload(request.url.toString());
                //     Fluttertoast.showToast(msg: "开始下载...");
                //   },
                //   textConfirm: "下载",
                //   textCancel: "取消",
                // );
              },
              shouldOverrideUrlLoading: (controller, navigationAction) async {
                var uri = navigationAction.request.url!;
                Get.log("request: ${navigationAction.request}");
                if (!["http", "https", "file", "chrome", "data", "javascript", "about"].contains(uri.scheme)) {
                  // if (await canLaunchUrl(uri)) {
                  // }
                  await launchUrl(uri);
                  return NavigationActionPolicy.CANCEL;
                }
                return NavigationActionPolicy.ALLOW;
              },
              onProgressChanged: (c, progress) {
                controller.setProgress(progress / 100);
              },
            ),
            Obx(() =>
            controller.progress.value < 1.0
                ? LinearProgressIndicator(
              value: controller.progress.value,
              color: Colors.green,
            )
                : Container()),
          ],
        ),
      ),
      onWillPop: () async {
        if (await _webViewcontroller?.canGoBack() == true) {
          await _webViewcontroller?.goBack();
          return false;
        }
        return true;
      },
    );
  }
}
